<?php

namespace Hkw\LargeFileUpload\Form;

use Dcat\Admin\Admin;
use Dcat\Admin\Form\Field;
use Helium\Sts\Facades\AliYunSTS;
use Qiniu\Auth;
use Storage;

class LargeFile extends Field
{
    protected $view = 'hkw-form-largefile::index';

    protected static $css    = [
        '@extension/hkw/large-file-upload/hkwlargefile.css'
    ];
    protected static $js     = [
        '@extension/hkw/large-file-upload/hkwlargefile.js'
    ];
    protected        $limit  = 0;//默认不限制
    protected        $accept = '*';//默认不限制

    public function render()
    {
        config('filesystems.default') == 'qiniu' && $this->qiniuConfig();
        config('filesystems.default') == 'oss' && $this->ossConfig();
        $this->addVariables(['accept' => $this->accept, 'limit' => $this->limit]);
        return parent::render();
    }

    public function accept($type_str)
    {
        $this->accept = $type_str;
        return $this;
    }

    public function limit(int $limit)
    {
        $this->limit = $limit;
        return $this;
    }


    private function qiniuConfig()
    {
        Admin::js('@extension/hkw/wang-editor/qiniu.min.js');
        $saveKey = config('admin.upload.directory.image') . '/$(etag)$(ext)';
        $policy  = [
            'saveKey'    => $saveKey,
            'returnBody' => json_encode([
                                            'status' => true,
                                            'data'   => [
                                                'id' => $saveKey, //不想要完整 url 的话改成 $saveKey 即可
                                            ],
                                        ]),
        ];
        $config  = [
            'region'     => 'qiniu.region.' . env('QINIU_REGION' , 'z2'),
            'upprotocol' => request()->isSecure() ? 'https' : 'http',
            'chunkSize'  => 1
        ];
        $auth    = new Auth(config('filesystems.disks.qiniu.access_key'), config('filesystems.disks.qiniu.secret_key'));
        $this->addVariables(['uptoken' => $auth->uploadToken(config('filesystems.disks.qiniu.bucket'), null, 3600, $policy), 'config' => $config]);
    }

    private function ossConfig()
    {
        Admin::js('@extension/hkw/wang-editor/aliyun-oss-sdk-6.16.0.min.js');
        $this->addVariables(AliYunSTS::token());
        $this->addVariables(['region' => str_replace('.aliyuncs.com', '', config('sts.endpoint'))]);
    }
}
